package projet.camping.sevlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import projet.camping.domaine.Habitation.Orientation;
import projet.camping.domaine.Habitation.TypeHabitation;
import projet.camping.exception.ArgumentInvalideException;
import projet.camping.exception.PartieNonExistantException;
import projet.camping.usecases.GestionPartie;

@WebServlet(urlPatterns = "/placement.html")
public class PlacerHabitation extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	@EJB
	GestionPartie ucc;
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.sendRedirect(resp.encodeRedirectURL("campingBattle.jsp"));
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		HttpSession session = req.getSession();
		PrintWriter out = resp.getWriter();
		
		String row = req.getParameter("row");
		String col = req.getParameter("col");
		String vertical = (String)req.getParameter("vertical");
		if("".equals(row) || "".equals(col) || "".equals(vertical)){
			out.write("ko");
		}
		if(row == null || col == null || vertical == null){
			out.write("ko");
		}
		System.out.println("row : " + row);
		System.out.println("col : "+col);
		System.out.println("vertical : " +vertical);
		Orientation o = Orientation.Horizontal;
		if(vertical.equals("true")){
			o = Orientation.Vertical;
		}
		int type = Integer.parseInt(req.getParameter("type"));
		TypeHabitation typeHab = null;
		
		switch(type){
		case 1: typeHab = TypeHabitation.Mobile_Home;
			break;
		case 2: typeHab = TypeHabitation.Bungalow;
			break;
		case 3: typeHab = TypeHabitation.CampingCar;
			break;
		case 4: typeHab = TypeHabitation.TenteLuxe;
			break;
		case 5: typeHab = TypeHabitation.TenteIgloo;
			break;
		}
		int temp = 0;
		try {
			temp = ucc.placerHabitation((String)session.getAttribute("nomPartie"), (String)session.getAttribute("login"), o, typeHab, Integer.parseInt(col), Integer.parseInt(row));
		} catch (NumberFormatException e) {
			
		} catch (PartieNonExistantException e) {
			out.write("partieNonExistante");
			System.err.println("la partie n'existe pas");
		} catch (ArgumentInvalideException e) {
			out.write("argument invalide");
		}
		if(temp == 1){
			out.write("ok");			
		}else{
			out.write("ko");			
		}
	}
}
